package com.koala.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DogOperations {
	// Database fields
		private KoalaDB dbHelper;
		private String[] DOG_TABLE_COLUMNS = { KoalaDB.PERSON_COLUMN_PHONE, KoalaDB.DOG_COLUMN_NAME, KoalaDB.DOG_COLUMN_BREED };
		private SQLiteDatabase database;

		public DogOperations(Context context) {
			dbHelper = new KoalaDB(context);
		}

		
		/** Open DB connection
		 * @throws SQLException
		 */
		public void open() throws SQLException {
			database = dbHelper.open();
		}

		
		/** Close DB connection
		 * 
		 */
		public void close() {
			dbHelper.close();
		}

		
		/** Add dog to the DB
		 * @param personPhone
		 * @param dogName
		 * @param dogBreed
		 * @return
		 */
		public Dog addDog(int personPhone, String dogName, String dogBreed) {

			ContentValues values = new ContentValues();

			values.put(KoalaDB.PERSON_COLUMN_PHONE, personPhone);
			values.put(KoalaDB.DOG_COLUMN_NAME, dogName);
			values.put(KoalaDB.DOG_COLUMN_BREED, dogBreed);
			
			open();
			
			/*long dogId = */database.insert(KoalaDB.DOG_TABLE_NAME, null, values);

			// now that the dog is created return it ...
			Cursor cursor = database.query(KoalaDB.DOG_TABLE_NAME,
					DOG_TABLE_COLUMNS, null, null, null, null, null);

			cursor.moveToFirst();

			Dog newDog = parseDog(cursor);
			cursor.close();
			close();
			return newDog;
		}

		
		/** Delete dog from the DB
		 * @param dog
		 */
		public void deleteDog(Dog dog) {
			int personPhone = dog.getPerson_phone();
			String dogName = dog.getDog_name();
			System.out.println("Dog deleted with name: " + dogName + " and phone: " + personPhone);
			open();
			database.delete(KoalaDB.DOG_TABLE_NAME, KoalaDB.PERSON_COLUMN_PHONE + " = "
					+ personPhone + " AND " + KoalaDB.DOG_COLUMN_NAME + " = " + dogName, null);
			close();
		}

		
		/** List all the dogs in the DB
		 * @return
		 */
		public List<Dog> getAllDogs() {
			List<Dog> dogs = new ArrayList<Dog>();
			
			open();
			Cursor cursor = database.query(KoalaDB.DOG_TABLE_NAME, 
					DOG_TABLE_COLUMNS, null, null, null, null, KoalaDB.DOG_COLUMN_NAME);

			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				Dog dog = parseDog(cursor);
				dogs.add(dog);
				cursor.moveToNext();
			}

			cursor.close();
			close();
			
			return dogs;
		}
		
		
		/** Create dog object from cursor
		 * @param cursor
		 * @return
		 */
		private Dog parseDog(Cursor cursor) {
			Dog dog = new Dog();
			dog.setPerson_phone(cursor.getInt(0));
			dog.setDog_name(cursor.getString(1));
			dog.setDog_breed(cursor.getString(2));
			return dog;
		}
}
